﻿using System;
using System.Collections.Generic;
using Aquarinum.Base.Infrastructure.EventBus.EventStore;
using Aquarinum.Base.Infrastructure.EventBus.Interfaces;
using Aquarinum.Base.Infrastructure.Ioc;
using Aquarinum.Util.Interface.Log;
using Newtonsoft.Json;

namespace Aquarinum.Base.Infrastructure.EventBus.Default
{
    /// <inheritdoc />
    public class DefaultHandlerRunner<T> : IHandlerRunner<T> where T : IEventData
    {
        public void ExcuteHandler(T message)
        {
            var store = DefalutInMemoryEventStore.GetInstance();
            var handlertypes = store.GetHandlersForEvent<T>();
            foreach (var handlertype in handlertypes)
            {
                IEnumerable<IEventHandler<T>> handlers = AquainumContainer.ResolveAll<IEventHandler<T>>();
                //todo 根据本地策略过滤无效的handler
                try
                {
                    //todo 增加分布式锁
                    foreach (var handler in handlers)
                    {
                        handler.HandleEvent(message);
                    }

                    //todo 释放分布式锁
                }
                catch (Exception e)
                {
                    AquainumContainer.Resolve<IAquarinumLogger>().Error(
                        $"DefaultHandlerRunner处理消息{JsonConvert.SerializeObject(message)}时出错", e);
                    //...TODO 根据策略进入重试队列或者死信队列
                }
                finally
                {
                    //todo 释放分布式锁
                }
            }
        }
    }
}